{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import ccxt\n",
    "import json\n",
    "import pandas as pd\n",
    "import traceback\n",
    "import time\n",
    "import math\n",
    "from datetime import datetime, timedelta\n",
    "\n",
    "def ccxt_fetch_binance_historical_candle_data(exchange, symbol, _time_interval, limit):\n",
    "    '''\n",
    "    获取制定币种k线信息\n",
    "    :param exchange:\n",
    "    :param symbol:\n",
    "    :param _time_interval:\n",
    "    :param limit:\n",
    "    :return:\n",
    "    '''\n",
    "\n",
    "    # 获取数据\n",
    "    get_records_times = math.ceil(limit/499)\n",
    "    data = retry_wrapper(exchange.fapiPublic_get_klines, act_name='获取币种K线数据',\n",
    "                         params={'symbol': symbol, 'interval': _time_interval, 'limit': 499})\n",
    "    get_records_times -= 1\n",
    "    timestamp = data[0][0]\n",
    "    while get_records_times >= 1:\n",
    "        get_records_times -= 1\n",
    "        ret1 = retry_wrapper(exchange.fapiPublic_get_klines, act_name='获取币种K线数据',\n",
    "                         params={'symbol': symbol, 'interval': _time_interval, 'limit': 499, 'endTime':timestamp})\n",
    "        if ret1:\n",
    "            ret1.pop(-1)\n",
    "            data = ret1 + data\n",
    "            timestamp = ret1[0][0]\n",
    "    # 整理数据\n",
    "    df = pd.DataFrame(data, dtype=float)\n",
    "    df.rename(columns={1: 'open', 2: 'high', 3: 'low', 4: 'close', 5: 'volume'}, inplace=True)\n",
    "    df['candle_begin_time'] = pd.to_datetime(df[0], unit='ms')\n",
    "    df['candle_begin_time_GMT8'] = df['candle_begin_time'] + timedelta(hours=8)\n",
    "    df = df[['candle_begin_time_GMT8', 'open', 'high', 'low', 'close', 'volume']]\n",
    "    print(f'获取{symbol}/{_time_interval}数据')\n",
    "    print(df.tail(2))\n",
    "\n",
    "    return df\n",
    "\n",
    "def retry_wrapper(func, params={}, act_name='', sleep_seconds=3, retry_times=5):\n",
    "    '''\n",
    "    需要在出错时不断重试的函数，如和交易所交互时。\n",
    "    :param func:重试的函数名\n",
    "    :param params: func的参数\n",
    "    :param act_name: 本次动作的名称\n",
    "    :param sleep_seconds: 报错后sleep的时间\n",
    "    :param retry_times: 最大出错重试次数\n",
    "    :return:\n",
    "    '''\n",
    "\n",
    "    for _ in range(retry_times):\n",
    "        try:\n",
    "            result = func(params=params)\n",
    "            return result\n",
    "        except Exception as e:\n",
    "            print(act_name, '报错，报错内容：', end='')\n",
    "            print('程序暂停（秒）：', sleep_seconds)\n",
    "            traceback.print_exc()\n",
    "            time.sleep(sleep_seconds)\n",
    "    else:\n",
    "        output_info = act_name + '报错重试次数超过上限，程序退出。\\n'\n",
    "        send_dingding_error_msg(output_info)\n",
    "        raise ValueError(output_info)\n",
    "\n",
    "\n",
    "BINANCE_CONFIG = {\n",
    "    'apiKey': '54j3ojRgK0EwJzHAGJRwhSkn232QFcKnh7L9hgO0oAbc2wBDqqr3zwRdKhSStDyD',\n",
    "    'secret': 'NXR8Ude0uf1iiLj58swgHeTiXoo0hTbhrVne9Os9iFPRFdHBlk9ycGPz80mw5MaL',\n",
    "    'timeout': 3000,\n",
    "    'rateLimit': 10,\n",
    "    'verbose': False,\n",
    "    'hostname': 'fapi.binance.com',\n",
    "    'enableRateLimit': False}\n",
    "exchange = ccxt.binance(BINANCE_CONFIG)\n",
    "host = '127.0.0.1'\n",
    "port = 7890\n",
    "proxy = {'http': 'http://%s:%d' % (host, port), 'https': 'http://%s:%d' % (host, port)}\n",
    "exchange.proxies = proxy\n",
    "symbol = 'BTCUSDT'\n",
    "_time_interval = '1h'\n",
    "limit = 498*4\n",
    "\n",
    "# data = retry_wrapper(exchange.fapiPublic_get_klines, act_name='获取币种K线数据',\n",
    "#                      params={'symbol': symbol, 'interval': _time_interval, 'limit': limit})\n",
    "\n",
    "# data = ccxt_fetch_binance_historical_candle_data(exchange, symbol, _time_interval, limit)\n",
    "# print(data)\n",
    "\n",
    "# data.drop_duplicates(subset=['candle_begin_time_GMT8'], inplace=True)\n",
    "# print(data)\n",
    "\n",
    "arr = exchange.fapiPrivateV2GetAccount()\n",
    "print(arr['positions'])\n",
    "long_position = 0\n",
    "short_position = 0\n",
    "for i in range(len(arr['positions'])):\n",
    "    amount = json.loads(arr['positions'][i]['notional'])\n",
    "    if amount < 0:\n",
    "        short_position += amount\n",
    "    else:\n",
    "        long_position += amount\n",
    "\n",
    "print('long_position:', long_position, 'short_position:', short_position)\n",
    "#\n",
    "# exchange_info = exchange.fapiPublic_get_exchangeinfo()\n",
    "# _symbol_list = [x['symbol'] for x in exchange_info['symbols'] if x['status'] == 'TRADING']\n",
    "# symbol_list = [symbol for symbol in _symbol_list if symbol.endswith('USDT')]\n",
    "#\n",
    "# position_risk = exchange.fapiPrivateV2_get_positionrisk()\n",
    "# print(position_risk)\n",
    "# position_risk = pd.DataFrame(position_risk, dtype='float')\n",
    "# print(position_risk)\n",
    "# position_risk.to_csv('/Volumes/Elements/alpha_v7.0.6/alpha_v7/src_product/position_risk.csv')\n",
    "# print(position_risk)\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "py38trading",
   "language": "python",
   "name": "py38trading"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
